<template>
  <div class="auth-container">
    <div class="auth-box">
      <h2>登录</h2>
      <el-form autoComplete="on" :model="loginForm" :rules="rules" ref="loginForm" class="auth-form">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            prefix-icon="el-icon-user"
            placeholder="用户名"
            autoComplete="on">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            prefix-icon="el-icon-lock"
            type="password"
            placeholder="密码"
            autoComplete="on"> 
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" class="auth-button">
            登录
          </el-button>
        </el-form-item>
        <div class="auth-options">
          <router-link to="/register">还没有账号？立即注册</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import store from '@/store'
import '@/assets/styles/auth.css'

export default {
  name: 'LoginPage',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            await this.$store.dispatch('user/login', this.loginForm)
            await this.$store.dispatch('user/getUserInfo')
            this.$message.success('登录成功')
            console.log(store.getters['user/isLoggedIn'])
            const redirect = this.$route.query.redirect || '/'
            this.$router.replace(redirect)
          } catch (error) {
            console.error(error)
          } finally {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
/* 移除所有样式，因为现在使用公共样式文件 */
</style>